<template>
  <div class="register-container">
    <div class="register-box">
      <h2>用户注册</h2>
      
      <div class="role-selector">
        <el-radio-group v-model="userRole" @change="handleRoleChange">
          <el-radio :label="1">教师注册</el-radio>
          <el-radio :label="2">学生注册</el-radio>
        </el-radio-group>
      </div>

      <div class="register-form">
        <el-form
          ref="formRef"
          :model="registerForm"
          :rules="rules"
          label-width="100px"
        >
          <!-- 基本信息 -->
          <el-form-item label="姓名" prop="name">
            <el-input v-model="registerForm.name" placeholder="请输入姓名" />
          </el-form-item>

          <el-form-item :label="userRole === 1 ? '工号' : '学号'" prop="userId">
            <el-input
              v-model="registerForm.userId"
              :placeholder="userRole === 1 ? '请输入工号' : '请输入学号'"
            />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="registerForm.email" placeholder="请输入邮箱（选填）" />
          </el-form-item>

          <!-- 教师特有字段 -->
          <template v-if="userRole === 1">
            <el-form-item label="所教学科" prop="subject">
              <el-select v-model="registerForm.subject" placeholder="请选择所教学科">
                <el-option label="语文" value="语文" />
                <el-option label="数学" value="数学" />
                <el-option label="英语" value="英语" />
                <el-option label="物理" value="物理" />
                <el-option label="化学" value="化学" />
                <el-option label="生物" value="生物" />
                <el-option label="历史" value="历史" />
                <el-option label="地理" value="地理" />
                <el-option label="政治" value="政治" />
              </el-select>
            </el-form-item>
          </template>

          <!-- 学生特有字段 -->
          <template v-if="userRole === 2">
            <el-form-item label="班级" prop="className">
              <el-select v-model="registerForm.className" placeholder="请选择班级">
                <el-option-group label="高一">
                  <el-option label="高一(1)班" value="高一(1)班" />
                  <el-option label="高一(2)班" value="高一(2)班" />
                  <el-option label="高一(3)班" value="高一(3)班" />
                </el-option-group>
                <el-option-group label="高二">
                  <el-option label="高二(1)班" value="高二(1)班" />
                  <el-option label="高二(2)班" value="高二(2)班" />
                  <el-option label="高二(3)班" value="高二(3)班" />
                </el-option-group>
                <el-option-group label="高三">
                  <el-option label="高三(1)班" value="高三(1)班" />
                  <el-option label="高三(2)班" value="高三(2)班" />
                  <el-option label="高三(3)班" value="高三(3)班" />
                </el-option-group>
              </el-select>
            </el-form-item>
          </template>

          <!-- 密码信息 -->
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="registerForm.password" 
              type="password"
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>
        
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
              show-password
          />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleRegister" :loading="isLoading">
            {{ isLoading ? '注册中...' : '注册' }}
            </el-button>
            <el-button @click="goToLogin">返回登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { register } from '@/api/auth'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const isLoading = ref(false)
const userRole = ref(1) // 默认为教师注册
    
    const registerForm = reactive({
      name: '',
  userId: '',
  phone: '',
  email: '',
  subject: '',
  className: '',
      password: '',
      confirmPassword: '',
  userRole: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度必须在2-50个字符之间', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请输入工号/学号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请选择所教学科', trigger: 'change' }
  ],
  className: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
      }

// 在组件挂载时检查URL参数
onMounted(() => {
  const roleParam = route.query.role
  if (roleParam && (roleParam === '1' || roleParam === '2')) {
    userRole.value = parseInt(roleParam)
    registerForm.userRole = parseInt(roleParam)
  }
})

// 处理角色切换
const handleRoleChange = (value) => {
  registerForm.userRole = value
  // 清空角色特有字段
  registerForm.subject = ''
  registerForm.className = ''
      }
      
// 处理注册
    const handleRegister = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    isLoading.value = true

    // 根据角色设置必填字段
    if (userRole.value === 1) {
      delete registerForm.className
    } else {
      delete registerForm.subject
    }
          
    const response = await register(registerForm)
          
    if (response.data && response.data.success) {
      ElMessage.success('注册成功')
      router.push('/login')
    } else {
      ElMessage.error(response.data?.message || '注册失败')
    }
  } catch (error) {
    console.error('注册失败:', error)
    if (error.response?.data?.success) {
      // 如果后端返回成功，但前端报错，说明是前端处理问题
      ElMessage.success('注册成功')
      router.push('/login')
    } else {
      ElMessage.error(error.response?.data?.message || '注册失败，请稍后重试')
    }
  } finally {
    isLoading.value = false
  }
}

// 跳转到登录页
    const goToLogin = () => {
  router.push('/login')
  }
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.register-box {
  width: 500px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.role-selector {
  margin-bottom: 20px;
  text-align: center;
}

.register-form {
  margin-top: 20px;
}

.el-form-item:last-child {
  margin-bottom: 0;
  text-align: center;
}

.el-button {
  margin: 0 10px;
}
</style> 